﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class ThreadPostingPage : PhoneApplicationPage
    {
        private Thread currentForum;

        public ThreadPostingPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void ManageButton(User user)
        {
            if (SavedUser.Instance.User.Id == user.Id)
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = true;
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
            }
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.THREAD))
            {
                currentForum = (Thread)PhoneApplicationService.Current.State[Config.THREAD];
                if (currentForum != null && currentForum.Id != null)
                {
                    textBlockJudul.Text = currentForum.Judul;
                    textBlockCreated.Text = currentForum.Created.ToString("dd/MMM/yyyy");
                    textBlockCreator.Text = currentForum.Creator.ToString();
                    textBlockIsiThread.Text = currentForum.Isi;

                    ManageButton(currentForum.Creator);
                }
                else
                {
                    textBlockCreated.Text = "";
                    textBlockCreator.Text = "";
                    textBlockIsiThread.Text = "";
                }
            }
        }

        private void buttonReply_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/ThreadReplyPage.xaml");
            PhoneApplicationService.Current.State[Config.THREAD] = currentForum;
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            if (currentForum != null && SavedUser.Instance.User.Id == currentForum.Creator.Id)
            {
                Utility.GotoPage(this, "/View/ThreadFormPage.xaml");
                PhoneApplicationService.Current.State[Config.THREAD] = currentForum;
            }
            else
            {
                MessageBox.Show("You don't have permission to change!");
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (currentForum != null && SavedUser.Instance.User.Id == currentForum.Creator.Id)
            {
                if (MessageBox.Show("Delete current thread?", "Delete Confirmation", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    DeleteCurrentThread(currentForum);
            }
            else
            {
                MessageBox.Show("You don't have permission to change!");
            }
        }

        private void DeleteCurrentThread(Thread forum)
        {
            string json = JsonConvert.SerializeObject(forum);
            string url = Config.Instance.THREAD_SERVICE_URL() + Config.DELETE_ACTION_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(deleteThread_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void deleteThread_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                if (e.Result.Contains("Success"))
                {
                    MessageBox.Show("Thread has been deleted.");
                    NavigationService.GoBack();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }


    }
}